<template>
    <div :class="`tech-change-address-page ${mode}`">
        <div class="location-input">
            <div class="location-action" @click="selectModal">
                <TechIcon name="location" />
                <div class="name title-color">{{defaultValue.showVal}}</div>
                <TechIcon name="arrow-bottom" />
            </div>
            <Field ref="searchInput" v-model="searchVal" placeholder="输入小区、写字楼、学校等" />
        </div>
        <div class="search-value-list" v-if="searchVal">
            <template v-if="searchList.length > 0">
                <AddressItem
                    v-for="(item, index) in searchList"
                    :key="index"
                    :addressInfo="item"
                    :searchVal="searchVal"
                    @select="selectedValue"
                    :mode="mode"
                    :theme="theme"
                    :styleMode="styleMode"
                />
            </template>
            <Empty v-else type="location" />
        </div>
        <template v-else>
            <div v-if="addressTip" :class="`auto-position ${mode}`">
                <div class="auto-title">当前定位地址</div>
                <div class="auto-address">
                    <div class="text-overflow" @click="selectLocation">{{addressTip}}</div>
                    <div class="auto-action" @click="resetLocation">
                        <TechIcon name="position" />重新定位
                    </div>
                </div>
            </div>
            <TechPanel class="my-address-list" v-if="addressList.length > 0" title="我的收货地址" type="gray" :mode="mode">
                <CellGroup>
                    <TechCell
                        v-for="item in addressList"
                        :key="item.id"
                        :border="true"
                        :title="`${item.contact}(${item.gender}) ${item.mobile}`"
                        :label="`${item.address}${item.building_number}`"
                        @click="() => selectUserAddress(item)"
                    />
                </CellGroup>
            </TechPanel>
        </template>
        <SelectAreaValue ref="selectArea" :defaultValue="defaultValue.code" @result="selectAreaResult" />
        <GoBack :mode="mode" />
    </div>
</template>

<script>
import { Field, CellGroup, Button } from 'vant';
import { mapActions, mapState, mapGetters } from 'vuex';
import { TechIcon, TechPanel, TechCell, Empty } from '@components/base';
import { GoBack } from '@components/biz';
import { getDefaultValue } from '@biztools/address';
import { getLocation } from '@common/environment';
import SelectAreaValue from '../common/components/SelectAreaValue';
import AddressItem from '../common/components/AddressItem';
import '@styles/biz/address';
import logger from '@common/logger';
import { getUiMode, getUiTheme, getUiStyleMode  } from '@biztools/info';
import { setTitle, navigateBack } from '@common/utils';
import { DEFAULT_MODE, DEFAULT_THEME, DEFAULT_STYLE_MODE } from '@constants/style';

export default {
    name: 'ShopChangeAddress', // 修改地址
    components: {
        TechPanel,
        CellGroup,
        TechCell,
        Button,
        Field,
        SelectAreaValue,
        TechIcon,
        Empty,
        AddressItem,
        GoBack,
    },
    computed: {
        ...mapState({
            searchList: state => state.shopAddress.searchList,
            addressTip: state => state.shopAddress.addressTip,
            addressInfo: state => state.shopAddress.addressInfo,
            addressList: state => state.shopAddress.addressList,
        }),
    },
    async created() {
        await this.getShopAddressList();
        setTitle('选择地址');
    },
    async mounted() {
        const location = await getLocation();
        // 匹配地址
        await this.matchShopAddress(location);
        setTimeout(() => {
            this.$refs.searchInput.focus();
        }, 10);
    },
    watch: {
        searchVal(newVal, oldVal) {
            clearTimeout(this.timer);
            this.timer = setTimeout(() => {
                this.startSearch();
            }, 500);
        },
    },
    data() {
        return {
            showSelectAddress: false,
            searchVal: '',
            defaultValue: getDefaultValue(this.address),
            // 获取设置的配置信息
            mode: getUiMode() || DEFAULT_MODE,
            theme: getUiTheme() || DEFAULT_THEME,
            styleMode: getUiStyleMode() || DEFAULT_STYLE_MODE,
        };
    },
    methods: {
        ...mapActions([
            'searchShopAddressList',
            'getShopAddressList',
            'matchShopAddress',
            'setShopAddressInfo',
        ]),
        async resetLocation() {
            const location = await getLocation();
            // 匹配地址
            await this.matchShopAddress(location);
        },
        startSearch() {
            if (this.searchVal) {
                this.searchShopAddressList({
                    city: this.defaultValue.searchVal,
                    keyword: this.searchVal,
                });
            }
        },
        selectUserAddress(item) {
            logger.info('当前选中的收货地址为:', item);
            this.setShopAddressInfo({
                address: `${item.address}${item.building_number}`,
                latitude: item.latitude,
                longitude: item.longitude,
                title: `${item.address}${item.building_number}`,
                city_code: item.city_code,
            });
            this.back();
        },
        selectLocation() {
            // alert('设置地址');
            this.selectedValue(this.addressInfo);
        },
        async selectedValue(item) {
            logger.info('设置的地址信息为', item);
            this.setShopAddressInfo(item);
            this.back();
        },
        async getStoreInfoAndAddress(location) {
            // 获取附近的地址
            await this.getNearbyStores({
                ...location,
            });
        },
        selectModal() {
            this.$refs.selectArea.show();
        },
        selectAreaResult(val) {
            logger.info('选择后的结果：', val);
            this.defaultValue = val;
        },
        back() {
            const { backUrl } = this.$route.query;
            if (backUrl) {
                this.$router.replace(backUrl);
            } else {
                this.$router.back();
            }
        },
    },
};
</script>
